package com.ge.med.cchelper.listener;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;

import org.eclipse.core.resources.IProject;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Text;

import com.ge.med.cchelper.Constants;
import com.ge.med.cchelper.bean.CSession;
import com.ge.med.cchelper.bean.Host;
import com.ge.med.cchelper.bean.Response;
import com.ge.med.cchelper.popup.job.BaseJob;
import com.ge.med.cchelper.popup.job.LsCheckoutJob;
import com.ge.med.cchelper.util.LogUtil;
import com.ge.med.cchelper.util.PropHelper;
import com.ge.med.cchelper.util.ReourceHelper;
import com.ge.med.cchelper.util.SSLhelper;
import com.ge.med.cchelper.util.StringHelper;

public class LoginListener implements Listener {
	CSession session;
	Shell dialogShell;
	Text ipt;
	Text userIdt;
	Text passwordt;
	Text viewNamet;
	Text patht;
	Text cleartoolt;
	Button submit;

	public LoginListener(Shell dialogShell, Text ipt, Text userIdt,
			Text passwordt, Text viewNamet, Text patht, Text cleartoolt,
			Button submit) {
		this.dialogShell = dialogShell;
		this.ipt = ipt;
		this.userIdt = userIdt;
		this.passwordt = passwordt;
		this.viewNamet = viewNamet;
		this.patht = patht;
		this.cleartoolt = cleartoolt;
		this.submit = submit;
		session = new CSession();
	}

	public void handleEvent(Event arg0) {

		submit.setEnabled(false);
		submit.setText("Waiting");
		String ip = ipt.getText();
		String userId = userIdt.getText();
		String password = passwordt.getText();
		String viewName = viewNamet.getText();
		String path = patht.getText();
		String cleartool = cleartoolt.getText();
		Host host = new Host();
		host.setIp(ip);
		host.setUserid(userId);
		host.setPassword(password);

		session.setHost(host);
		session.setViewName(viewName);
		session.setVobRoot(path);
		session.setCleartool(cleartool);

		IProject currentProject = ReourceHelper.getProject();
		String projectId = currentProject.getName();
		session.setProjectId(projectId);

		ReourceHelper resource = ReourceHelper.getResource();
		resource.addSession(projectId, session);

		String confdir = currentProject.getLocation().toOSString();
		String confFile = confdir + File.separator + PropHelper.CONFIG_FILE;
		File file = new File(confFile);
		if (!file.exists()) {
			try {
				file.createNewFile();
			} catch (IOException e1) {
				LogUtil.err("create conf file fail.");
			}
		}
		HashMap<String, String> map = new HashMap<String, String>();
		map.put(PropHelper.HOST, ip);
		map.put(PropHelper.USERNAME, userId);
		map.put(PropHelper.VIEWNAME, viewName);
		map.put(PropHelper.VOBDIR, path);
		map.put(PropHelper.CLEARTOOL, cleartool);
		PropHelper.writeProperties(confFile, map);

		BaseJob login = new BaseJob("login clearcase server") {
			protected IStatus start(IProgressMonitor arg0) {
				SSLhelper helper = new SSLhelper(session);
				try {
					int res = -1;
					try{
					  res = helper.testConnect();
					}catch(Exception e){
						LogUtil.err(e.getMessage());
						return Status.CANCEL_STATUS;
					}
					if (res == 0) {
						LogUtil.out("login successful.");
						Response res3 = helper.execute("pwd");
						String pwd = res3.getContent().toString().trim();
						String realPwd = StringHelper.matchPath(pwd);
						if(realPwd.trim().equals("")){
							LogUtil.err("read working directory error.");
						}
						
						IProject currentProject = ReourceHelper.getProject();
						String vobPath = currentProject.getProject().getLocation().toOSString()+ File.separator + Constants.VOB;
						File vobDir = new File(vobPath);
						if(!vobDir.exists()){
							LogUtil.out("create local vob:"+vobPath);
							vobDir.mkdirs();
							try {
								currentProject.refreshLocal(
										IProject.DEPTH_INFINITE, null);
							} catch (CoreException e1) {
								e1.printStackTrace();
								LogUtil.err("refresh failed." + e1.getMessage());
							}
						}else{
							//get check out list.
							LsCheckoutJob cojob = new LsCheckoutJob("Checking CHECKOUT status...",session);
							cojob.schedule();
						}
						
						session.setLoginpwd(realPwd);
						dialogShell.getDisplay().syncExec(new Runnable() {
							public void run() {
								dialogShell.dispose();
							}
						});
						
					} else {
						LogUtil.err("Login failed.");
						return Status.CANCEL_STATUS;
					}
				} catch (Exception e) {
					e.printStackTrace();
					LogUtil.err("Login failed.cause:" + e.getMessage() + "");
					return Status.CANCEL_STATUS;
				} finally {
					if (!dialogShell.isDisposed()){
						dialogShell.getDisplay().syncExec(new Runnable() {
							public void run() {
								submit.setEnabled(true);
								submit.setText("Login");
							}
						});
					}
				}
				return Status.OK_STATUS;
			}
		};
		login.schedule();

	}

}
